﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyUtils.Pool
{
    /// <summary>
    /// 简易内存池(约束: 泛形必须为class)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class SimpleObjectPool<T> where T : class
    {
        private readonly ConcurrentBag<T> _objects;
        private readonly Func<T> _objectGenerator;

        /// <summary>
        /// 构建对象池
        /// </summary>
        /// <param name="objectGenerator"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public SimpleObjectPool(Func<T> objectGenerator)
        {
            this._objectGenerator = objectGenerator ?? throw new Exception("构造对象池函数中 实例构造Func不能为空");
            this._objects = new ConcurrentBag<T>();
        }

        public void Alloc(int size)
        {
            if (size <= 0)
                throw new Exception($"Alloc({size}) 参数错误");
            for (int i = 0; i < size; i++)
                this._objects.Add(this._objectGenerator());
        }

        /// <summary>
        /// 获取对象池中实例
        /// </summary>
        /// <param name="item"></param>
        public void Get(out T item)
        {
            if (_objects.TryTake(out item) == false)
                item = this._objectGenerator();
        }

        /// <summary>
        /// 归还实例到对象池中
        /// </summary>
        /// <param name="item">待归还的实例</param>
        public void Return(T item)
        {
            this._objects.Add(item);
        }

        /// <summary>
        /// 获取池内实例数量
        /// </summary>
        /// <returns></returns>
        public int Count()
        {
            return this._objects.Count;
        }
    }
}
